import qs from 'qs'
import axios from 'axios'
import { getToken, removeToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'
import router from '@/router'
import store from '@/store'

const service: any = axios.create({
  baseURL: '/prod-api',
  timeout: 1000 * 60
})
// 请求拦截器

service.interceptors.request.use(
  (config: any) => {
    if (config.method.toLocaleLowerCase() == 'post') {
      // if (!config.headers['Content-Type']) {
      //   config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      // }
      if (
        config.type == 'default' ||
        (config.type != 'json' && config.headers['Content-Type'] == null)
      ) {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        config.transformRequest = [
          (obj: any) => qs.stringify(obj, { indices: false })
        ] // 解决post传输格式问题。
      } else {
        config.headers = {
          'Content-Type': 'application/json;charset=UTF-8'
        }
      }
    }
    //添加token
    // config.headers['BDSOFT-TOKEN'] = '03a1e91e-f0aa-4fdf-a5cc-24e716cf883b'
    // const storage = sessionStorage.getItem('userInfo')
    //   ? JSON.parse(sessionStorage.getItem('userInfo') as string)
    //   : ''
    // storage?.token && (config.headers['BDSOFT-TOKEN'] = storage?.token)
    // if (store.getters.token) {
    //
    config.headers['BDSOFT-TOKEN'] = getToken() || ''
    // }
    return config
  },
  (err: any) => {
    return Promise.reject(err)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: any) => {
    const { data } = response
    if (data.code == 200) {
      return data
    } else if (data.code == 401) {
      removeToken()
      router.push('/login')
    } else {
      ElMessage({
        message: data.message,
        showClose: true,
        offset: 130,
        duration: 1800,
        type: 'warning'
      })
    }
  },
  (err: any) => {
    if (err.data.code == 401) {
      removeToken()
      router.push('/login')
    } else {
      return err
    }
  }
)

export default (url: string, data = {}, method = 'POST', type: string) => {
  return new Promise((resolve, rej) => {
    service({ url, method, data, type })
      .then((res: any) => {
        if (res.code == 200) {
          resolve(res)
        } else {
          rej(res)
        }
      })
      .catch((err: any) => {
        rej(err)
      })
  })
}
